import time

import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class NeimengguWlcbsfzsrmzfD744Policy(BaseTaxPolicySpider):
    name = "neimenggu_wlcbsfzsrmzf_d744_policy"

    province: str = "内蒙古自治区"  # 取表格
    city: str = "乌兰察布市"  # 取表格
    county: str = "丰镇市"  # 取表格
    park: str = "None"  # 取表格
    source: str = "乌兰察布市丰镇市人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.fengzhen.gov.cn/zcwjkfw/index.html"  # 注明入口网址，以便后续排错

    host_url = url.split('.gov.cn')[0] + '.gov.cn'
    headers = {
        "Content-Type": "application/json, text/plain, */*",
        "Referer": f"{host_url}/zcwjkfw/index.html",
    }
    api_url = f"{host_url}/apiv2/Blocks/getDocument"

    def start_requests(self):

        data = {
            "page_size": "20",
            "page": "1",
            "orgs_id": "0",
            "keyword": "",
            "theme_type": "全部",
            "start_time": "",
            "end_time": "",
            "word_num": "",
            "start_time1": "",
            "end_time1": "",
            "keyword_type": "0"
        }

        url = self.api_url + "?" + urlencode(data)
        yield scrapy.FormRequest(url, callback=self.parse_list, meta={"data": data}, )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        print(response.json()['data'])
        for elem in response.json()['data']['data']:
            item = Item()
            source_url = f'{self.host_url}/ArticleDetails/' + base64.b64encode(
                f'{elem["id"]}/yu/{elem["id"]}/'.encode()).decode(
                "utf8") + f'{int(time.time() * 1000 % 10000)}/96206.html?menu_id={elem["menu_id"]}'
            # print(source_url)
            item['source_url'] = source_url
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pulish_time']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield scrapy.Request(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta.get('data')
            total_page = response.json()['data'].get('total')
            for page_num in range(2, math.ceil(int(total_page) / 20) + 1):
                data['page'] = str(page_num)
                url = self.api_url + "?" + urlencode(data)
                yield response.follow(url, callback=self.parse_list, headers=self.headers, meta={"data": data})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_wlcbsfzsrmzf_d744_policy".split())
